#include "sensor.h"
#include "ntc.h"
#include "controller.h"
#include <math.h>
#define TEMP_FILTER_NUM 10
#define REFER_VOLTAGE   3300

static uint8_t tempTab[TEMP_FILTER_NUM];
static uint8_t tempTabIndex = 0xFF;
static uint16_t tempSum;
static uint16_t temp;

static void sensor_temp_process(void)
{
    uint16_t  volt;
    float  Rt;           //测得实际电阻值
    float  _temp;        //温度值
    float  R = 10000;    //热敏电阻NTC103
    float  B = 3950;     //NTC固有参数
    float  T2= (273.15+25.0);
    static uint8_t errCnt;

    volt = (ntc_get_adVal() / 4096.0f) * REFER_VOLTAGE; /*换算成电压*/

    /* 开路或短路 */
    if(volt > 3000 || volt < 200)
    {
        errCnt++;
        if(errCnt > 10)
        {
            set_fault(1);
            set_page(PAGE_ERROR);
        }
        return ;
    }
    Rt = 10200.0f * volt / (REFER_VOLTAGE - volt);
    _temp = 1 / (logf(Rt / R) / B + 1 / T2);
    _temp = (_temp - 273.15);        //最终的温度值

    if(tempTabIndex == 0xFF)
    {
        tempTabIndex = 1;
        for(uint8_t i = 0; i < TEMP_FILTER_NUM; i++)
        {
            tempTab[i] = _temp;
        }
        tempSum = _temp * TEMP_FILTER_NUM;
    }

    tempSum = tempSum - tempTab[tempTabIndex] + _temp;
    tempTab[tempTabIndex++] = _temp;
    tempTabIndex %= TEMP_FILTER_NUM;
    temp = tempSum / TEMP_FILTER_NUM;
}

uint16_t sensor_get_temp(void)
{
    return temp;
}

void sensor_process(void)
{
    sensor_temp_process();
    set_tempSmp(temp);
}
